import time
from io import BytesIO
import urllib
from urllib import parse
import oss2
import requests
from bs4 import BeautifulSoup

from common.file_util import make_file_name

from settings import Config


def update_img_srcs(content):
    soup = BeautifulSoup(content, "html.parser")
    images_list = soup.find_all("img")
    for image in images_list:
        # 一条代码直接时间戳获取
        file_name = str(time.mktime(time.localtime(time.time()))) + ".png"
        res = requests.get(image["src"])
        file_data = BytesIO(res.content)
        img_url = aliyunoss.put_object(file_name, file_data)
        print(image["src"])
        content = str(content).replace(image["src"], img_url)
    return content


class AliyunOss(object):

    def __init__(self):
        self.access_key_id = Config.ALIYUN_ACCESS_ID
        self.access_key_secret = Config.ALIYUN_SECRET_ACCESS_KEY
        self.auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket_name = Config.ALIYUN_BUCKET
        self.endpoint = Config.ALIYUN_HOST
        self.bucket = oss2.Bucket(self.auth, self.endpoint, self.bucket_name)

    def put_file(self, name, file):
        """
        :param name: 文件名
        :param file: 文件
        :return:
        """
        # Endpoint以杭州为例，其它Region请按实际情况填写。
        result = self.bucket.put_object(name, file)
        # HTTP返回码。
        print('http status: {0}'.format(result.status))
        # 请求ID。请求ID是请求的唯一标识，强烈建议在程序日志中添加此参数。
        print('request_id: {0}'.format(result.request_id))
        # ETag是put_object方法返回值特有的属性。
        print('ETag: {0}'.format(result.etag))
        # HTTP响应头部。
        print('date: {0}'.format(result.headers['date']))

    def put_object_from_file(self, name, file):
        """
        上传本地文件
        :param name: 需要上传的文件名
        :param file: 本地文件名
        :return: 阿里云文件地址
        """
        self.bucket.put_object_from_file(name, file)
        return "https://{}.{}/{}".format(self.bucket_name, self.endpoint, name)

    def put_object(self, name, file):
        save_name = make_file_name(name)
        key = "/".join(["uploads", "nxshare", save_name])
        # 上传二进制文件
        result = self.bucket.put_object(key=key, data=file)
        if result.status == 200:
            img_name = urllib.parse.unquote(
                result.resp.response.url.replace(Config.ALIYUN_OUTER_NET,
                                                 Config.ALIYUN_INNER_NET, 1))
            return img_name
        return ""


aliyunoss = AliyunOss()
# response = requests.get("https://www.opencart.cn/storage/uploads/image/2022/07/20/d062d10673db0a185c81233d1a2c48d5.jpg")
# img_file = BytesIO(response.content)
# img = aliyunoss.put_object("d062d10673db0a185c81233d1a2c48d5.jpg", img_file)
# # img = aliyunoss.put_object_from_file("传到阿里云上的图片名", "本地图片路径")
# print(img)
